#include "ssicloud_service_policy.h"

ssicloud::ServicePolicy::ServicePolicy()
    : ListObject<ServicePolicyLNode>(LQ_BASE_URL "/servicePolicy/queybypage"
                           , OBJECT_NAME_ServicePolicy
                           , NetUrl::NET_HTTP_METHOD_POST)
{
    mUrl.appendHeader(HEADER_JSON);
    mUrl.appendHeader(HEADER_TOKEN);
    mUrl.append("status", "1");
}

bool ssicloud::ServicePolicy::requestAll(int pageNum, int pageSize)
{
    snprintf(m_body, sizeof(m_body),
             "{\"status\": 1,"
             "\"pageNum\": %d,"
             "\"pageSize\": %d"
             "}", pageNum, pageSize);
    mUrl.appendBody(m_body);
    return obtain();
}

void ssicloud::ServicePolicy::profile()
{
    ListTable<ServicePolicyLNode>::iterator it = mNodes.begin();
    GEN_Printf(LOG_INFO, "---------服务政策-分页查询-------");

    for (; it != mNodes.end(); ++it)
    {
         GEN_Printf(LOG_DUMP, "标题:%s, 描述: 'html标签语言，太多了不打印了', 创建时间:%s",
                    it->title.string(), /*it->contant.c_str(),*/ it->createTime.c_str());
    }
    GEN_Printf(LOG_INFO, "---------完成-------");
}

int ssicloud::ServicePolicy::genResult(NetBuffer *data)
{
    int ret = KL_DATA_PRISER_OK;
    // GEN_Printf(LOG_DEBUG, "size: %lu\n%s", data->size(), (char *)data->buffer());
    cJSON *root = cJSON_Parse((char *)data->buffer(), data->size());
    cJSON *dataJson = cJSON_GetObjectItem(root, "data");
    if (dataJson)
    {
        cJSON *records = cJSON_GetObjectItem(dataJson, "records");
        if (records) {
            for (cJSON *item = records->child; NULL != item; item = item->next )
            {
                ServicePolicyLNode tmp;

                JSON_VALUETRING_SWAP_BYTESTRING(item, title, tmp.title);
                JSON_VALUETRING_SWAP_BYTESTRING(item, contant, tmp.contant);
                JSON_VALUETRING_SWAP_BYTESTRING(item, thumbnail, tmp.thumbnail);
                JSON_VALUETRING_SWAP_BYTESTRING(item, createTime, tmp.createTime);
                JSON_VALUETRING_SWAP_BYTESTRING(item, updateTime, tmp.updateTime);
                JSON_VALUETRING_SWAP_BYTESTRING(item, userName, tmp.userName);

                // GEN_Printf(LOG_DEBUG, "items size=%d", tmp.items.size());
                mNodes.push_back(tmp);
            }
        }

        if (mNodes.empty())
        {
            ret = KL_DATA_PRISER_EMPTY;
        } else
        {
            profile();
        }
    } else
    {
        GEN_Printf(LOG_ERROR, "priser failed, size: %lu\n%s", data->size(), data->buffer());
        ret = KL_DATA_PRISER_JSOC_ERROR;
    }

    cJSON_Delete(root);
    return ret;
}
